<template>
  <div class="main-box">
    <div class="card content-box w-full">
      <TableContainer :is-page="false">
        <template #searchCard>
          <SearchFrom :search-event="handleSearchEvent" />
        </template>
        <template #btnLeft>
          <el-button v-auth="['admin:dept:add']" type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增
          </el-button>
        </template>
        <el-table :data="[...tableData]" row-key="id" empty-text="暂无数据" v-bind="{ ...gridOptions, ...$attrs }">
          <template #empty>
            <span>暂无数据</span>
          </template>
          <el-table-column
            v-for="item in gridOptions.columns"
            v-bind="{ ...item, ...$attrs }"
            :type="item.type ? item.type : 'default'"
            :label="item.label"
            :prop="item.prop"
            :key="item.prop"
            :width="item.width"
            :fixed="item.fixed ? item.fixed : false"
            :header-align="item.headerAlign ? item.headerAlign : 'left'"
          >
            <template #default="{ row }">
              <el-tag v-if="item.slots == 'deptType'" :type="row.deptType == 'COMPANY' ? 'primary' : 'success'">
                {{ deptTypeDict[row.deptType] }}
              </el-tag>
              <el-tag v-if="item.slots == 'status'" :type="row.status ? 'primary' : 'info'">
                {{
                  {
                    1: "启用",
                    0: "停用"
                  }[row.status]
                }}
              </el-tag>
              <div class="w-full flex items-center justify-center" v-if="item.slots === 'controls'">
                <el-button v-auth="['dept:edit:btn']" link type="primary" @click="handleEdit(row)">
                  <el-icon>
                    <EditPen />
                  </el-icon>
                  修改
                </el-button>
                <el-button link v-auth="['dept:remove:btn']" type="danger" @click="handleDelete(row)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
                <el-button link v-auth="['dept:add:btn']" type="primary" @click="handleAdd($event, row)">
                  <el-icon>
                    <CirclePlus />
                  </el-icon>
                  新增下级
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </TableContainer>
    </div>
    <DeptAdd ref="deptAddRef" @close="handleClose"></DeptAdd>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useComponentRef } from "@/hooks/useComponentRef";
import SearchFrom from "./components/SearchFrom.vue";
import { getDeptDetail, getDeptList, removeDept } from "@/api/modules/dept";
import { Dept } from "@/api/interface";
import { getDictDataObjByType } from "@/api/modules/dict";
import TableContainer from "@/components/TableContainer/index.vue";
import { useTableConfig } from "@/hooks/useTable";

const tableData = ref<Dept.IDept[]>([]);

const DeptAdd = defineAsyncComponent(() => import("./components/Add.vue"));
const deptAddRef = useComponentRef(DeptAdd);

const deptTypeDict = ref({});
let searchForm = reactive<Dept.IDeptParams>({});

const { gridOptions } = useTableConfig({
  columns: [
    { prop: "deptName", label: "机构名称", width: 200 },
    { prop: "deptCode", label: "机构代码" },
    { prop: "fullName", label: "机构全称" },
    { prop: "orderNum", label: "排序号" },
    { prop: "deptType", label: "机构类型", slots: "deptType" },
    {
      prop: "status",
      label: "状态",
      slots: "status"
    },
    { prop: "leader", label: "负责人" }
  ],
  controlsWidth: 240
});

onMounted(() => {
  initListData();
});

const getDeptTypeDict = async () => {
  const { data } = await getDictDataObjByType("SYSTEM_DEPT_TYPE");
  deptTypeDict.value = data;
};

const getList = async () => {
  const { data } = await getDeptList({ ...searchForm });
  tableData.value = data.records;
};

const handleSearchEvent = (form: Dept.IDeptParams) => {
  searchForm = form;
  getList();
};

const handleAdd = (event: MouseEvent, row?: Dept.IDept) => {
  deptAddRef.value?.openDialog("add", { parentId: row?.id });
};

const handleEdit = async (row: Dept.IDept) => {
  try {
    if (!row.id) return;
    const { data } = await getDeptDetail(row.id);
    console.log(deptAddRef.value);
    deptAddRef.value?.openDialog("edit", data);
  } catch (e) {
    console.error(e);
  }
};

const handleDelete = async (row: Dept.IDept) => {
  try {
    if (!row.id) return;
    const result = await ElMessageBox.confirm("确定删除该条数据吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    if (result !== "confirm") return;
    await removeDept(row.id);
    ElMessage.success("删除成功");
    initListData();
  } catch (e) {
    console.error(e);
  }
};

const initListData = () => {
  getList();
  getDeptTypeDict();
};

const handleClose = () => {
  initListData();
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
